<template>
  <el-form label-width="80px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="SPU名称"
        v-model="props.spuInfo.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="(props.spuInfo.id as number)">
        <el-option
          v-for="tm in tmList"
          :key="tm.id"
          :value="tm.id"
          :label="tm.tmName"
          >{{ tm.tmName }}</el-option
        >
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="SPU名称"
        rows="4"
        v-model="props.spuInfo.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="spuImageList as UploadUserFile[]"
        :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select
        :placeholder="`还有${newSaleAttrList.length}个未选择`"
        :style="{ marginRight: '30px' }"
        v-model="tempSaleAttr"
      >
        <el-option
          v-for="attr in newSaleAttrList"
          :key="attr.id"
          :value="`${attr.id}:${attr.name}`"
          :label="attr.name"
        />
      </el-select>
      <el-button
        type="primary"
        size="default"
        icon="ele-Plus"
        @click="addSaleAttr"
        :disabled="newSaleAttrList.length <= 0 || !tempSaleAttr"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table border stripe :data="spuSaleAttrList">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row, $index }">
            <!--  -->
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-2"
              closable
              :disable-transitions="true"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <!-- @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm" -->
            <el-input
              v-if="row.isEdit"
              class="ml-1 w-20"
              size="small"
              ref="eleIpt"
              @blur="handleInputConfirm(row)"
              v-model="row.iptValue"
            />
            <el-button
              v-else
              type="primary"
              size="small"
              @click="changToEdit(row)"
              icon="ele-Plus"
              >添加属性值</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              size="default"
              @click="spuSaleAttrList.splice($index, 1)"
              icon="ele-Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="default"
        @click="saveAttrList"
        :disabled="spuSaleAttrList.length <= 0"
        >保存</el-button
      >
      <el-button type="default" size="default" @click="emit('setState', 0)"
        >取消</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
import { onMounted, ref, nextTick, computed } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  requestBaseSaleAttrList,
  requestSaveSpuInfo,
  requestSpuImgList,
  requestSpuSaleAttrList,
  requestUpdateSpuInfo,
  type BaseSaleAttrListType,
  type SpuImageListType,
  type SpuInfoType,
  type SpuSaleAttrItemType,
  type SpuSaleAttrListType,
} from "@/api/spu";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import {
  requestAllTmList,
  requestTrademarkList,
  type reqTrademarkReturnItemType,
  type reqTrademarkReturnRecordsType,
} from "@/api/trademark";

//拿到env的环境变量
const baseUrl = import.meta.env.VITE_API_URL;

//初始化操作
onMounted(() => {
  getAllUseData();
});

//接收自定义事件函数
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();

//接收porps传递的数据
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
//照片墙的事件函数
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//定义一些数据用来保存请求回的数据
//品牌列表
const tmList = ref<reqTrademarkReturnRecordsType>([]);
//所有销售属性列表
const saleAttrList = ref<BaseSaleAttrListType>([]);
//图片列表
const spuImageList = ref<SpuImageListType>([]);
//当前spu属性列表
const spuSaleAttrList = ref<SpuSaleAttrListType>([]);

//封装一个函数用来判断用户是增加或是修改
const getAllUseData = async () => {
  //我们判断prop接收数据中是否存在id,如果存在则是修改,不是则是增加
  if (!props.spuInfo.id) {
    //进入当前判断则证明是添加
    try {
      //请求品牌列表和所有销售属性列表
      const result1 = await requestAllTmList();
      tmList.value = result1;
      const result2 = await requestBaseSaleAttrList();
      saleAttrList.value = result2;
    } catch (e) {
      ElMessage.error("请求失败");
    }
  } else {
    //进入到else则证明是修改,我们需要请求品牌列表和所有销售属性列表,图片列表,当前spu属性列表
    //并发请求
    const p1 = requestAllTmList();
    const p2 = requestBaseSaleAttrList();
    const p3 = requestSpuImgList(props.spuInfo.id);
    const p4 = requestSpuSaleAttrList(props.spuInfo.id);
    try {
      //Promise.all静态方法 当所有请求都成功则返回成功的promise 值为成功的信息
      const result = await Promise.all([p1, p2, p3, p4]);

      tmList.value = result[0];
      //所有销售属性列表
      saleAttrList.value = result[1];
      //图片列表
      spuImageList.value = result[2];
      //照片数据
      spuImageList.value.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      //当前spu销售属性列表
      spuSaleAttrList.value = result[3];
      //我们还需要给spu的详细信息添加一个isEdit未来用作观察或编辑模式切换
      spuSaleAttrList.value.forEach((item) => {
        item.isEdit = false;
        item.iptValue = "";
      });
      //console.log(spuSaleAttrList, "spuSaleAttrList");
    } catch (e) {
      ElMessage.error("请求失败");
    }
  }
};

//计算属性销售属性
const newSaleAttrList = computed(() => {
  //对所有的销售属性进行一个过滤
  return saleAttrList.value.filter((item1) => {
    //判断如果下面当前table中已经有了的销售属性 则下拉框不在显示拥有的
    //使用every进行判断所有都满足条件返回true,有一个不满足条件为false
    return spuSaleAttrList.value.every((item2) => {
      return item1.name !== item2.saleAttrName;
    });
  });
});

//定义一个空数据用来el-select和el-option数据双向绑定
const tempSaleAttr = ref("");
//定义一个spu的详细信息数据将来插入到table中
const tempSpuAttr = ref<SpuSaleAttrItemType>({
  baseSaleAttrId: null,
  id: null,
  saleAttrName: "",
  spuId: null,
  spuSaleAttrValueList: [],
});
//点击添加销售属性
const addSaleAttr = () => {
  //解构下拉框的值
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":");
  //赋值
  tempSpuAttr.value = {
    baseSaleAttrId: +baseSaleAttrId as number,
    id: null,
    saleAttrName: saleAttrName,
    spuId: null,
    spuSaleAttrValueList: [],
    isEdit: false,
  };
  //插入到当前spu销售属性列表
  spuSaleAttrList.value.push(tempSpuAttr.value);

  //清空下拉框中的数据
  tempSaleAttr.value = "";
};

//定义一个同名的eleIpt用来保存ipt信息
const eleIpt = ref<HTMLInputElement>();
//点击Button的事件函数
const changToEdit = (row: SpuSaleAttrItemType) => {
  //切换为编辑模式
  row.isEdit = true;
  //自动获取焦点
  nextTick(() => {
    eleIpt.value?.focus();
  });
};
//当输入框失去焦点的事件函数
const handleInputConfirm = (row: SpuSaleAttrItemType) => {
  //row是当前这一条spu信息
  //切换为观察模式
  row.isEdit = false;
  //获取输入框的值
  let Value = row.iptValue as string;

  //判断输入的值是否为空
  if (!Value.trim()) {
    //如果输入的值为空则不添加到属性值数据中
    row.isEdit = false;
    ElMessage.error("输入的属性值不能为空");
    return;
  }
  //判断输入的值是否有重复
  const isRepeat = row.spuSaleAttrValueList.some((item) => {
    return item.saleAttrValueName === Value;
  });
  if (isRepeat) {
    //进入该判断则证明是有重复的
    ElMessage.error("添加的属性值已存在");
    //清空上一次输入的值
    row.iptValue = "";
    return;
  }

  //我们要把新添加的属性值放到数组中
  //定义一个新的spu属性值列表
  const newSpuSaleAttrValueList = {
    baseSaleAttrId: row.baseSaleAttrId as number,
    saleAttrValueName: row.iptValue as string,
  };
  row.spuSaleAttrValueList.push(newSpuSaleAttrValueList);
  //清空上一次输入的值
  row.iptValue = "";
};

//点击保存手机表单数据发送请求
const saveAttrList = async () => {
  //如果img自己上传了话 保存在response中
  //收集照片信息列表
  const newImgList = spuImageList.value.map((item) => {
    //判断是否有response
    if (item.response) {
      //如果存在
      return {
        imgName: item.name as string,
        imgUrl: item.response.data,
      };
    } else {
      return {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
      };
    }
  });

  //清除我们自己添加的两个属性 isEdit和iptValue
  spuSaleAttrList.value.forEach((item) => {
    delete item.isEdit;
    delete item.iptValue;
  });

  //将整理好的数据添加到spuInfo中
  props.spuInfo.spuImageList = newImgList;
  props.spuInfo.spuSaleAttrList = spuSaleAttrList.value;
  console.log(props.spuInfo);

  //判断是新增请求还是修改请求
  if (props.spuInfo.id) {
    //如果id存在的话则证明是修改请求
    try {
      await requestUpdateSpuInfo(props.spuInfo);
      ElMessage.success("保存成功");
    } catch (e) {
      ElMessage.error("保存失败");
    }
  } else {
    try {
      await requestSaveSpuInfo(props.spuInfo);
      ElMessage.success("保存成功");
    } catch (e) {
      ElMessage.error("保存失败");
    }
  }
  //返回到spuList页面
  emit("setState", 0);
};
</script>
<!-- Spu照片墙的逻辑
const fileList = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
]); -->
